/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

package com.ControlEscolar.AdminExam;

import com.ControlEscolar.Beans.Exam;
import com.ControlEscolar.Beans.Student;
import com.ControlEscolar.Exceptions.ServiceExp;
import com.ControlEscolar.Services.ExamReportService;
import com.ControlEscolar.Services.ExamService;
import com.ControlEscolar.Services.ProfessorService;
import com.ControlEscolar.Services.StudentService;
import com.ControlEscolar.Services.SubjectService;
import java.sql.Date;
import java.util.ArrayList;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import org.apache.struts.action.ActionForm;
import org.apache.struts.action.ActionForward;
import org.apache.struts.action.ActionMapping;
import org.apache.struts.actions.MappingDispatchAction;

/**
 *
 * @author Jalbs
 */
public class AdminExam extends MappingDispatchAction{
    private static final String MODIFY="m";
    ArrayList results=new ArrayList();
    ExamService service = new ExamService();
    ExamReportService report = new ExamReportService();




    public void getExamInform (ActionMapping mapping, ActionForm form, HttpServletRequest request, HttpServletResponse response)throws Exception{
        String[] selectedExam=request.getParameterValues("id");
        report.writeExamFileReport(selectedExam);

    }

    public void modifyGrade (ActionMapping mapping, ActionForm form, HttpServletRequest request, HttpServletResponse response)throws Exception{

          ExamForm examForm = (ExamForm)form;
          Exam exam=formToBean(examForm);
          examForm.setAction("");          
          try{
          service.updateGrade(exam);
          response.getWriter().print("success");
          }catch(Exception ex){
            ex.printStackTrace();
            response.getWriter().print("No se puede modificar esta calificacion");
          }

    }       

    public ActionForward getExamToModify(ActionMapping mapping, ActionForm form, HttpServletRequest request, HttpServletResponse response)throws Exception{
          String examKey=request.getParameter("id");
          Exam exam = new Exam();
          exam = service.getExam(examKey);          
          ExamForm examForm = (ExamForm)form;
          beanToForm(examForm, exam);         
          relationIdName(examForm);
          examForm.setAction(MODIFY);
          return mapping.findForward("success");
    }

    public ActionForward getAllExams(ActionMapping mapping, ActionForm form, HttpServletRequest request, HttpServletResponse response)throws Exception{
          results=service.getExamList();
          ArrayList<ExamForm> formResults=relationsIdName(results);
          HttpSession session = request.getSession();
          session.setAttribute("completeGradeList", formResults);
          return mapping.findForward("success");
    }

    public ActionForward addExams(ActionMapping mapping, ActionForm form, HttpServletRequest request, HttpServletResponse response)throws Exception{
          String fileUrl=request.getParameter("fileUrl");
          System.out.println("La direccion del archivo es : "+fileUrl);
          service.readFileExam(fileUrl.trim());
          ((ExamForm)form).setAction("m");
          return mapping.findForward("success");
    }

    private Exam formToBean(ExamForm examForm) {
        Exam exam = new Exam();
        exam.setDates(stringToDate(examForm.getDates()));
        exam.setExamGrade(Float.parseFloat(examForm.getExamGrade()));
        exam.setExamType(examForm.getExamType());
        exam.setID_Exam(Integer.parseInt(examForm.getID_Exam()));
        exam.setID_Professor(Integer.parseInt(examForm.getID_Professor()));
        exam.setID_Request(Integer.parseInt(examForm.getID_Request()));
        exam.setStudentKey(examForm.getStudentKey());
        exam.setSubjectKey(examForm.getSubjectKey());
        exam.setID_Curriculum(Integer.parseInt(examForm.getID_Curriculum()));
        return exam;
    }

    private void beanToForm(ExamForm examForm, Exam exam) {
        examForm.setDates(dateToString(exam.getDates()));
        examForm.setExamGrade(Float.toString(exam.getExamGrade()));
        examForm.setExamType(exam.getExamType());
        examForm.setID_Exam(Integer.toString(exam.getID_Exam()));
        examForm.setID_Professor(Integer.toString(exam.getID_Professor()));
        examForm.setID_Request(Long.toString(exam.getID_Request()));
        examForm.setStudentKey(exam.getStudentKey());
        examForm.setSubjectKey(exam.getSubjectKey());
        examForm.setID_Curriculum(exam.getID_Curriculum()+"");
    }

    private Date stringToDate(String yearMonthDay){
        if(yearMonthDay!=null){
            String[] splittedDate=yearMonthDay.split("/");
            if(splittedDate.length==3){
                Date date=Date.valueOf(""+splittedDate[0]+"-"+splittedDate[1]+"-"+splittedDate[2]);
                return date;
            }
            splittedDate=yearMonthDay.split("-");
            if(splittedDate.length==3){
                Date date=Date.valueOf(""+splittedDate[0]+"-"+splittedDate[1]+"-"+splittedDate[2]);
                return date;
            }
        }
        return null;
    }

    private String dateToString(Date date){
        String[] ymd=date.toString().split("-");
        String s=""+(ymd[0]+"-"+ymd[1]+"-"+ymd[2]);
        return s;
    }

    private ArrayList<ExamForm> relationsIdName(ArrayList results) {
        try{
            ArrayList<ExamForm> examFormList=new ArrayList<ExamForm>();
            StudentService studentService=new StudentService();
            ProfessorService professorService=new ProfessorService();
            SubjectService subjectService=new SubjectService();
            for(int index=0;index<results.size();index++){
                ExamForm tableForm=new ExamForm();
                Exam exam=(Exam)results.get(index);
                beanToForm(tableForm, exam);

                String studentKey=exam.getStudentKey();
                int profKey=exam.getID_Professor();
                String subjectKey=exam.getSubjectKey();

                Student student=studentService.getStudent(studentKey);

                String studentCompleteName=student.getFirstLastName()+
                        " "+student.getSecondLastName()+" "+student.getName();
                String profName=professorService.getProfessor(profKey).getProfessor_Name();
                String subjectName=subjectService.getSubject(subjectKey).getSubjectName();

                tableForm.setStudentName(studentCompleteName);
                tableForm.setProfName(profName);
                tableForm.setSubjectName(subjectName);
                examFormList.add(tableForm);
            }
            return examFormList;
        }catch(Exception ex){
            ex.printStackTrace();
            ArrayList<ExamForm> examFormList=new ArrayList<ExamForm>();
            return examFormList;
        }
    }

    private void relationIdName(ExamForm examForm) {
        try {
            StudentService studentService = new StudentService();
            ProfessorService professorService = new ProfessorService();
            SubjectService subjectService = new SubjectService();

            String studentKey=examForm.getStudentKey();
            String profKey=examForm.getID_Professor();
            String subjectKey=examForm.getSubjectKey();

            int professorKey=Integer.parseInt(profKey.trim());

            Student student=studentService.getStudent(studentKey);

            String studentName=student.getFirstLastName()+
                        " "+student.getSecondLastName()+" "+student.getName();
            String profName=professorService.getProfessor(professorKey).getProfessor_Name();
            String subjetcName=subjectService.getSubject(subjectKey).getSubjectName();

            examForm.setStudentName(studentName);
            examForm.setProfName(profName);
            examForm.setSubjectName(subjetcName);
        } catch (ServiceExp ex) {
            Logger.getLogger(AdminExam.class.getName()).log(Level.SEVERE, null, ex);
        }
    }

}
